package cn.coconet.clothingguide.model;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomChatModel {

    private final String modelApiUrl;
    private final String apiKey;
    private final RestTemplate restTemplate;

    public CustomChatModel(String modelApiUrl, String apiKey) {
        this.modelApiUrl = modelApiUrl;
        this.apiKey = apiKey;
        this.restTemplate = new RestTemplate();
    }

    // 方法名保持为chat，返回值改为自定义的CustomChatResponse
    public CustomChatResponse chat(List<ChatMessage> messages) {
        try {
            Map<String, Object> requestBody = buildCustomRequest(messages);
            String rawResponse = sendRequest(requestBody);
            ChatMessage responseMessage = processResponseToChatMessage(rawResponse);
            // 使用自定义响应类的构造器（不再冲突）
            return new CustomChatResponse(responseMessage, true);
        } catch (Exception e) {
            ChatMessage errorMessage = UserMessage.from("请求处理失败：" + e.getMessage());
            return new CustomChatResponse(errorMessage, false);
        }
    }

    // 以下辅助方法保持不变
    private Map<String, Object> buildCustomRequest(List<ChatMessage> messages) {
        Map<String, Object> request = new HashMap<>();
        StringBuilder userInput = new StringBuilder();

        for (ChatMessage message : messages) {
            String text = message.toString()
                    .replace("SystemMessage[", "")
                    .replace("UserMessage[", "")
                    .replace("]", "")
                    .trim();

            if (message instanceof dev.langchain4j.data.message.SystemMessage) {
                request.put("system", text);
            } else if (message instanceof UserMessage) {
                userInput.append(text).append("\n");
            }
        }

        request.put("user", userInput.toString().trim());
        Map<String, Object> params = new HashMap<>();
        params.put("temperature", 0.7);
        request.put("params", params);

        return request;
    }

    private String sendRequest(Map<String, Object> requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
        return restTemplate.postForObject(modelApiUrl, request, String.class);
    }

    private ChatMessage processResponseToChatMessage(String rawResponse) {
        String replyContent = extractReplyFromRawResponse(rawResponse);
        String filteredContent = filterInvalidContent(replyContent);
        String formattedContent = formatReply(filteredContent);
        return UserMessage.from(formattedContent);
    }

    private String extractReplyFromRawResponse(String rawResponse) {
        if (rawResponse.contains("\"reply\":")) {
            return rawResponse.split("\"reply\":")[1].replaceAll("[\"}]", "").trim();
        }
        return rawResponse;
    }

    private String filterInvalidContent(String content) {
        String[] forbiddenWords = {"测试", "广告"};
        for (String word : forbiddenWords) {
            content = content.replace(word, "***");
        }
        return content;
    }

    private String formatReply(String content) {
        return "【服装导购】" + content + "\n\n国庆活动：满200减50";
    }
}